# Copyright (c) 2009 Lemur Consulting Ltd.
# 
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

""" 
$ python searchxraw.py <dbname> <qsize> <iters>
"""

import xapian
import sys
import random
import time
import search_timer

fdict = open('usr/share/dict/british-english')
words = [x.strip().lower() for x in fdict if "'" not in x]
fdict.close()

db = xapian.Database(sys.argv[1])
dbsize = db.get_doccount()
enq = xapian.Enquire(db)
random.seed()
search_timer.start();

total = 0
for i in xrange(int(sys.argv[3])):
    terms = []
    for j in xrange(int(sys.argv[2])):
        terms.append(random.choice(words))
    
    query = xapian.Query(xapian.Query.OP_OR, terms)
    enq.set_query(query)
    mset = enq.get_mset(0, 10)  #, dbsize)
    total += mset.get_matches_estimated()
    
    # should this print be in the loop? won't it add to the search time?
    if i % 100 == 0:
        print i, terms, total
    
search_timer.stop();
print 'total matches:', total
print "searching took %s microseconds" % search_timer.micro()
# Need to avoid divide-by-zero here
print (1000*int(sys.argv[3])) / (search_timer.milli()), ' queries/s'